package tools.global.view {
	import org.aswing.AbstractListCell;
	import org.aswing.Component;
	import org.aswing.JButton;
	import org.aswing.JLabel;
	import org.aswing.JList;
	import org.aswing.JPanel;

	import flash.events.MouseEvent;

	/**
	 * 支持额外排序的列表
	 * @author zhangming.luo
	 */
	public class SortableCell extends AbstractListCell {
		private var container : JPanel;
		private var label : JLabel;
		private var upButton : JButton;
		private var downButton : JButton;
		private var index : int;
		private var list : JList;

		override public function getCellComponent() : Component {
			return getCell();
		}

		override public function setCellValue(value : *) : void {
			super.setCellValue(value);
			label.setText(value);
		}

		override public function setListCellStatus(list : JList, isSelected : Boolean, index : int) : void {
			this.list = list;
			this.index = index;
			super.setListCellStatus(list, isSelected, index);
			if (isSelected) {
				upButton.visible = true;
				downButton.visible = true;
				upButton.setEnabled(index > 0);
				downButton.setEnabled(index < list.getModel().getSize() - 1);
			} else {
				upButton.visible = false;
				downButton.visible = false;
			}
		}

		private function getCell() : Component {
			if (!container) {
				container = new JPanel();
				container.setOpaque(true);
				container.append(label = new JLabel());
				container.append(upButton = new JButton("↑"));
				container.append(downButton = new JButton("↓"));
				upButton.setPreferredHeight(10);
				downButton.setPreferredHeight(10);
				upButton.addEventListener(MouseEvent.CLICK, onUp);
				downButton.addEventListener(MouseEvent.CLICK, onDown);
			}
			return container;
		}

		private function onDown(event : MouseEvent) : void {
			var e : SortEvent = new SortEvent(SortEvent.CHANGE);
			e.oldIndex = index;
			e.newIndex = index + 1;
			list.dispatchEvent(e);
		}

		private function onUp(event : MouseEvent) : void {
			var e : SortEvent = new SortEvent(SortEvent.CHANGE);
			e.oldIndex = index;
			e.newIndex = index - 1;
			list.dispatchEvent(e);
		}
	}
}
